//
//  InstallLayerEMA.h
//  client
//
//  Created by galileoliu on 1/7/2019.
//
//

#ifndef InstallLayerEMA_h
#define InstallLayerEMA_h

#include "cocos2d.h"
#include "extensions/cocos-ext.h"
#include "InstallLayer.h"
#ifdef USE_EMACDN
#include "UpdateSpeedCounter.hpp"
#include "EMA/EMAInfoString.hpp"
#endif

USING_NS_CC;
using namespace cocos2d::extension;

class InstallLayerEMA : public InstallLayer
{
public:
    CREATE_FUNC(InstallLayerEMA);

    InstallLayerEMA();

    virtual ~InstallLayerEMA();

    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();

#ifdef USE_EMACDN
    virtual void update(float);
    EMAInfoString& getEMAInfoString();
private:
    void initAssetsManager();
	void startUpdate(Ref* sender);
    void onProgress(AssetsManagerEx::State curVersionStage, float percent, int64_t totalSize, int64_t nowSize);
    void onError(AssetsManagerEx::State curVersionStage, EventAssetsManagerEx::EventCode errorCode, EventAssetsManagerEx* event = nullptr);
    void onUpdateSuccess();
    void continueUpdate();
    void stopUpdate();
    void clear();
    void setResourceVersion(const std::string& version);
    
  
    void _onInitSdkSuccess();
    void _onInitSdkFail();
    void _checkSdkInit();
    void _addSdkInitEventListener();
    void _removeSdkInitEventListener();
    
    std::string getDownSizeShowString(int64_t totalSize, int64_t nowSize);
    
    std::vector<std::string> _cdnUrlList;
    std::string _cdnUrl;
    int _cdnUrlIndex;
    
    bool _waitMessageBox;
    bool _shouldStop;
    bool _flagShowPatchSizeDialog;
    
    EventAssetsManagerEx::EventCode _lastErrorCode;
    AssetsManagerEx::State _curStage;
    
    UpdateSpeedCounter _speedCounter;
    EMAInfoString _emaInfoString;
    EMAErrorString _emaErrorString;
    
    EventListenerCustom* _listener;
    
#endif
    virtual void goStart();
    virtual void goExit();
    virtual void goNext();
    
private:
    std::string _newResourceVersion;
    
    AssetsManagerEx* _am;
    EventListenerAssetsManagerEx* _amListener;
    double _downLoadTime;
};

#endif
